package org.yunai.swjg.server.core.thread;

import org.slf4j.Logger;
import org.yunai.swjg.server.core.service.Online;
import org.yunai.swjg.server.core.service.OnlineContextService;
import org.yunai.yfserver.common.LoggerFactory;
import org.yunai.yfserver.spring.BeanManager;

/**
 * 操作其他玩家接口
 * User: yunai
 * Date: 13-5-21
 * Time: 下午8:03
 */
public abstract class AbstractOtherPlayerOperation {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoggerFactory.Logger.player, AbstractOtherPlayerOperation.class);

    private static OnlineContextService onlineContextService;
    private static CrossThreadOperationService crossThreadOperationService;
    static {
        onlineContextService = BeanManager.getBean(OnlineContextService.class);
        crossThreadOperationService = BeanManager.getBean(CrossThreadOperationService.class);
    }

    /**
     * 玩家编号
     */
    private final Integer playerId;

    public AbstractOtherPlayerOperation(Integer playerId) {
        this.playerId = playerId;
    }

    public Integer getPlayerId() {
        return playerId;
    }

    public final void doOnline() {
        Online online = onlineContextService.getPlayer(playerId);
        if (online == null) {
            LOGGER.error("[doOnline] [player({}) now is offline].", playerId);
            crossThreadOperationService.execute(this);
            return;
        }
        doOnlineImpl(online);
    }

    protected abstract void doOnlineImpl(Online online);

    public void doOffline() {
        if (onlineContextService.getPlayer(playerId) != null) { // 防止执行的时候，玩家又在线了。不考虑玩家上线又下线，又下线这样反复调用的情况
            LOGGER.error("[doOffline] [player({}) now is online].", playerId);
            crossThreadOperationService.execute(this);
            return;
        }
        doOfflineImpl();
    }

    protected abstract void doOfflineImpl();
}
